package models.writers;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import com.csvreader.CsvWriter;
import models.Transaction;
import models.parsers.HsbcCreditParser;
import org.apache.log4j.Logger;
import utils.DateUtil;

public class TransactionListWriter {
    public List<Transaction> transactions;
    static Logger logger = Logger.getLogger(HsbcCreditParser.class);

    public TransactionListWriter(List<Transaction> transactions) {
        this.transactions = transactions;
    }

    public void writeToFile(String filename) throws IOException {

        boolean includeHeaders = !new File(filename).exists();
        sentToCsvWriter(new FileWriter(filename, true), includeHeaders, transactions);
    }

    public String writeToString() {

        boolean includeHeaders = true;
        StringWriter writer = new StringWriter();
        sentToCsvWriter(writer, includeHeaders, transactions);
        return writer.getBuffer().toString();
    }

    private void sentToCsvWriter(Writer writer, boolean includeHeaders, List<Transaction> transactionList) {
        if (transactionList == null || transactionList.size() == 0) {
            logger.error(" no transactions to write");
            return;
        }

        try {
            CsvWriter csvOutput = new CsvWriter(writer, ',');

            if (includeHeaders) {
                csvOutput.write("date");
                csvOutput.write("label");
                csvOutput.write("amount");
                csvOutput.endRecord();
            }

            for (Transaction transaction : transactionList) {
                csvOutput.write(DateUtil.formatIsoDate(transaction.date));
                csvOutput.write(transaction.label);
                csvOutput.write(transaction.amount.toPlainString());
                csvOutput.endRecord();
            }

            csvOutput.close();
        } catch (IOException e) {
            logger.error(e);
        }
    }
}
